// pages/personal_detail/personal_detail.js
const request = require('../../utils/promise.js');
const util = require('../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    genderArr: [
      { value: 1, label: '男'},
      { value: 2, label: '女'}
    ],
    genderIndex: 0,
    diploma: 0,
    diplomaArr: ['小学', '初中', '高中', '专科', '本科', '研究生', '博士'],
    region: null,
    referee: null,
    phoneModal: false,
    birthYear: '',  // 出生年份
    currYear: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const currDate = util.formatDate(new Date());
    const currYear = currDate.substring(0, 4);
    this.setData({
      currYear: currYear
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.reqUserInfo();
  },

  /**
   * 页面被用户分享时执行
   */
  onShareAppMessage() {
    return {
      title: '更多个人信息'
    }
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: '更多个人信息'
    }
  },

  /**
   * 获取用户编辑的信息
   */
  reqUserInfo() {
    request.GET('/user/userInfo', {openId: wx.getStorageSync('openId')}).then(res => {
      // console.log(res)
      if (res.data.resCode==200) {
        var region = null;
        if (res.data.userInfo['country'] && res.data.userInfo['province'] && res.data.userInfo['city']) {
          region = res.data.userInfo['country'] +'·'+ res.data.userInfo['province'] +'·'+ res.data.userInfo['city'];
        }

        // 性别下拉框初始化
        let gender = res.data.userInfo['gender'];
        let arrIndex = (this.data.genderArr || []).findIndex((item) => item.value == gender);
        // 性别未知，则默认男
        let genderIndex = arrIndex == -1 ? 0 : arrIndex;
        
        this.setData({
          userInfo: res.data.userInfo,
          region: region,
          genderIndex: genderIndex,
          referee: res.data.userInfo['referee']? res.data.userInfo['referee']: null,
          diploma: res.data.userInfo['diploma']? res.data.userInfo['diploma']: null,
          birthYear: res.data.userInfo['birthday']? res.data.userInfo['birthday']: null
        })

      } else {
        wx.showToast({
          title: '获取数据异常',
          icon: 'error',
          duration: 1500
        })
      }
    })
  },

  /**
   * 保存更新用户信息
   */
  reqSaveUserInfo(value, type) {
    const param = {
      userId: wx.getStorageSync('userId'), 
      valueStr: value,
      colType: type
    }
    request.GET('/user/save/edit', param).then(res => {
      // console.log(res)
      if (res.data.resCode==200) {
        wx.showToast({
          title: '保存成功',
          icon: 'none',
          duration: 1000
        })
      } else {
        wx.showToast({
          title: '保存异常失败',
          icon: 'error',
          duration: 1500
        })
      }
    })
  },

  /**
   * 选择出生日期
   */
  bindPickerBirthChange(e) {
    this.setData({
      birthYear: e.detail.value
    })
    this.reqSaveUserInfo(this.data.birthYear, 10);
  },

  /**
   * 跳转设置姓名或手机号
   */
  gotoSetFullnameOrPhone(e) {
    const type = e.currentTarget.dataset.type;
    if (type==8) {
      wx.navigateTo({
        url: '/pages/personal_edit/personal_edit?type='+ type,
      })
    } else {
      // wjc 暂时屏蔽手机号修改
      // this.setData({
      //   phoneModal: true
      // })
    }
  },

  /**
   * 性别选择
   */
  bindPickerGenderChange(e) {
    let nowIndex = e.detail.value;
    let genderValue = this.data.genderArr[nowIndex].value;
    this.setData({
      genderIndex: nowIndex
    })

    this.reqSaveUserInfo(genderValue, 4);
  },

  /**
   * 学历选择
   */
  bindPickerDiplomaChange(e) {
    this.setData({
      diploma: e.detail.value
    })
    this.reqSaveUserInfo(this.data.diploma, 5);
  },

  /**
   * 地区选择
   */
  bindPickerRegionChange(e) {
    this.setData({
      region: e.detail.value[0] +'·'+ e.detail.value[1] +'·'+ e.detail.value[2]
    })
    this.reqSaveUserInfo(this.data.region, 6);
  },

  /**
   * 跳转添加推荐人
   */
  gotoAddRefereeUser() {
    // 是否已存在推荐人
    if (!this.data.userInfo['refereeUserId']) {
      wx.navigateTo({
        url: '/pages/referee/referee',
      })
    }
  },

  /**
   * 隐藏授权 modal
   */
  clickHideModal() {
    this.setData({
      phoneModal: false
    })
  },

   /**
   * 授权获取用户手机号
   */
  getPhoneNumber(e) {

    this.setData({
      phoneModal: false
    })

    console.log(e)
    // 绑定微信注册登录
    if (e.detail.errMsg=='getPhoneNumber:ok') {
      const param = {
        encryptedStr: e.detail.encryptedData,
        ivStr: e.detail.iv,
        openId: wx.getStorageSync('openId'),
        sessionKey: wx.getStorageSync('sessionKey'),
        rawDataStr: JSON.stringify(this.data.userInfo)
      }

      request.GET('/user/wx/auth/register', param).then(res => {
        // console.log(res)
        if (res.data.resCode==200) {
          // 注册登录成功, 设置缓存数据
          wx.showToast({
            title: '授权登录成功',
            icon: 'success',
            duration: 1000
          })
          this.reqUserInfo();
        } else {
          wx.showToast({
            title: '服务器异常',
            icon: 'error',
            duration: 1500
          })
        }
      })
    }

    // 用户取消授权, 或取消绑定手机号
    if (e.detail.errMsg.indexOf("deny")>=0 || e.detail.errMsg=="getPhoneNumber:fail user cancel bind") {
      wx.navigateTo({
        url: '/pages/personal_edit/personal_edit?type=9',
      })
    }
  },

})